package com.tengyun.middleplatform.trade.etl.controller;

import com.tengyun.data.Result;
import com.tengyun.middleplatform.trade.etl.service.IDataHandleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.stream.Stream;

/**
 * @Author: likailun
 * @Description: 手动触发
 * @Date: create in 2022/3/7 10:52 上午
 */
@RestController
@RequestMapping("/open")
@Validated
@Slf4j
public class OpenController {

    @Resource
    private IDataHandleService iDataHandleService;

    /**
     * 手动触发任务
     *
     * @return
     */
    @GetMapping(value = "/handler")
    public Result handler(@RequestParam("date") String date) {
        LocalDate toDay = LocalDate.now();
        if (!StringUtils.isEmpty(date)) {
            toDay = LocalDate.parse(date, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        }
        iDataHandleService.currentDayData(toDay);
        return Result.success();
    }

    /**
     * 手动触发任务
     *
     * @return
     */
    @GetMapping(value = "/handlerBatch")
    public Result handlerBatch(@RequestParam("startDate") String startDate, @RequestParam("endDate") String endDate) {
        LocalDate start = LocalDate.parse(startDate, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        LocalDate end = LocalDate.parse(endDate, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        Stream.iterate(start, localDate -> localDate.plusDays(1))
                .limit(ChronoUnit.DAYS.between(start, end) + 1)
                .forEach(date -> {
                    iDataHandleService.currentDayData(date);
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                });
        return Result.success();
    }
}
